﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MSScriptControl;
using WatiN.Core;
using WebAutomation.Browsers;

namespace WebAutomation
{
    public class ScriptCommand : CommandBase
    {
        private WebBrowserObject _browserObject;
        private string[] _commandParameters;
        private string _url;
        private string _testRepo;
        private string _testResultLocation;
        private string _dbConnString;
        private System.Data.DataSet _dataFromDB;
        private TestLineResult _testLineResult;


        public ScriptCommand(WebBrowserObject browserObject)
        {
            this.Initialize(browserObject);

        }
        public override bool ExecuteCommand(WebBrowserObject browserObject, string[] parameter, string url, string testRepo, string testResultLocation, string dbConnString, ref System.Data.DataSet dataFromDB, ref TestLineResult testLineResult, ref bool stopTest, WebAutoUtils.ITestDataExceptionRules testDataExceptionRules)
        {
            _browserObject = browserObject;
            _commandParameters = parameter;
            _url = url;
            _testRepo = testRepo;
            _testResultLocation = testResultLocation;
            _dbConnString = dbConnString;
            _dataFromDB = dataFromDB;
            _testLineResult = testLineResult;
            
            string command = parameter[0];
            testLineResult.LineCommand = command;
            testLineResult.LineParameter = parameter[1];
            if (this.BrowserObject == null)
            {
                this.BrowserObject = browserObject;
            }
            string execStatement = parameter[1];
            bool result = false;
            if (string.IsNullOrEmpty(execStatement))
            {
                _testLineResult.LineMessage = "Error.You must specify script to execute.";
                _testLineResult.LinePassed = false;
            }else
            {
                execStatement = GetCorrectExecuteStatement(parameter[1], testDataExceptionRules);
                try
                {
                    ScriptControl script = new ScriptControl();
                    script.Language = "VBScript";
                    script.AllowUI = true;
                    switch (command.ToLower())
                    {
                        case "exec":
                            script.AddCode(execStatement);
                            result = Convert.ToBoolean(script.Run("ExecScript",new object[]{0}));
                            _testLineResult.LinePassed = result;
                            break;

                    }




                }
                catch (Exception ex)
                {
                    _testLineResult.IsFrameworkError = true;
                    testLineResult.LineMessage = "Error." + ex.Message + "." + ex.StackTrace;
                    _testLineResult.LinePassed = false;
                }
            }

            return _testLineResult.LinePassed;
        }

        public virtual string GetCorrectExecuteStatement(string execStatement, WebAutoUtils.ITestDataExceptionRules testDataExceptionRules)
        {
            string returnValue = execStatement;
            string testName = "";
            string testFileName = "";
            string testDescription = "";
            string testResultsLocation = "";
            string browser = "";
            string url = "";
            string testRepo = "";
            string dbConnString = "";
            
            //strip out commands
            string testString = execStatement;// "if (Element?Exist|ctl00_ContentPlaceHolder1_Login1_UserName)=false then (EndTest?End|) end if)";
            string[] testStringArray = testString.Split(' ');
            Dictionary<string, string> listOfCommands = new Dictionary<string, string>();
            foreach(var items in testStringArray)
            {
                if (items.StartsWith("("))
                {
                    if (!listOfCommands.ContainsKey(items))
                    {
                        string origItem = items;
                        string[] newItemArray = origItem.Split(')');
                        string newItem = newItemArray[0].Replace("(", "");
                        listOfCommands.Add(newItem, "");
                    }
                }

            }

            //Get test command
            Dictionary<string, string> listOfCommandsTmp = new Dictionary<string, string>();

            foreach(var items in listOfCommands)
            {
                string[] commandArray = items.Key.Split('?');
                string command = commandArray[0].Replace("'","");
                string[] commandParameter = commandArray[1].Replace("'","").Split('|');
                ICommand iCommand = TestCommands.GetTestCommand(command);
                bool stopTest = false;
                bool result=TestCommands.DoExecuteTestCommand(iCommand, _browserObject, commandParameter, _url, _testRepo,
                                                  _testResultLocation, _dbConnString, ref _dataFromDB,
                                                  ref _testLineResult,ref stopTest, testDataExceptionRules);
                listOfCommandsTmp.Add(items.Key,result.ToString().ToLower());
            }

            listOfCommands = new Dictionary<string, string>();
            listOfCommands = listOfCommandsTmp;


            foreach(var items in listOfCommands)
            {
                if(items.Key.StartsWith("'"))
                {
                    testString = testString.Replace(items.Key, "'" + items.Value + "'");
                }else
                {
                    testString = testString.Replace(items.Key, items.Value);    
                }
                

            }
            testString = testString.Replace("(", "").Replace(")", "");
            if (testString.Contains("then true"))
            {
                testString = testString.Replace("then true", "then \ntrue\n");
            }
            if (testString.Contains("then false"))
            {
                testString = testString.Replace("then false", "then \nfalse\n");
            }
            //if (testString.Contains("else true"))
            //{
            //    testString = testString.Replace("else true", "else \ntrue\n");
            //}
            //if (testString.Contains("else false"))
            //{
            //    testString = testString.Replace("else false", "else \nfalse\n");
            //}
            if (testString.Contains("return true"))
            {
                testString = testString.Replace("return true", "\nreturn true\n");
            }
            if (testString.Contains("return false"))
            {
                testString = testString.Replace("return false", "\nreturn \false\n");
            }
            testString = testString.Replace("else", "\nelse\n").Replace("end if", "\nend if\n").Replace("(", "").Replace(")", "");

            string funcString = "Function ExecScript(val)";
            funcString += "\n\n" + testString.Replace("return", "ExecScript=");
            funcString += "End function";
            return funcString;

        }

    }
}
